import {upDateStateJwtKey} from "../localStorages/localStorageUesrData.js";
import {RenderRoomPlayer, RenderRoomTitle, renderSpectators} from "./Rendering.js";
import {ModifyTheRoomToastButton} from "./functionClick.js";

// 玩家 修改房间 修改房间模态框 提交
document.getElementById('SaveYourChanges').onclick = ModifyTheRoomToastButton;

window.onload = async function () {
    const jwtKey = (await upDateStateJwtKey()).count.jwtKey;

    const socket = new WebSocket("/ws/roomsMember", ["Bearer", jwtKey]);
    socket.onerror=function (){
        console.log("测试错误")
    }
    socket.onclose =function (){
        //window.location.href = "/";
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        socket.close();
    }

    socket.addEventListener("message", function (event) {

        let {data} = JSON.parse(event.data);
        // 渲染网页标题
        RenderRoomTitle(data.roomName, data.roomUuid, data.currentUserData.userStatus === "ROOM_OWNER")

        // 循环渲染玩家 
        let playerList = document.getElementById('player-list');

        playerList.innerHTML = '';
        data.roomAllPlayerInformation.forEach(e => {
            // 当前用户是否为房主
            let whetherCurrentUserIsOwnerHouse = data.currentUserData.userStatus === "ROOM_OWNER";
            // 是否当前用户
            let whetherOrNotYouAreACurrentUser = e.userId === data.currentUserData.userId;
            // 房主
            let whetherTheHomeownerIsOrNot = e.userStatus === "ROOM_OWNER";
            // 是否准备
            let whetherToPrepareOrNot = e.awaitStatusEnum !== "WAITING";

            let htmlDivElement = RenderRoomPlayer(e.userId, e.userImages, e.userName, e.userColor, whetherCurrentUserIsOwnerHouse, whetherOrNotYouAreACurrentUser, whetherTheHomeownerIsOrNot, whetherToPrepareOrNot);

            playerList.prepend(htmlDivElement)
        })

        // 渲染观众席
        let spectatorList = document.getElementById('spectator-list');
        spectatorList.innerHTML = '';
        data.roomAudienceInformation.forEach(e => {
            let spectators = renderSpectators(e.userImages, e.userName, e.userStatus === "ROOM_OWNER")
            spectatorList.prepend(spectators)
        })
    })
}
